package org.fund.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.fund.base_service.domain.SysUser;
import org.fund.base_service.service.ISysUserService;
import org.fund.common.core.domain.BaseResult;
import org.fund.common.core.model.RegisterBody;
import org.fund.common.redis.RedisCache;
import org.fund.framework.service.EmailService;
import org.fund.framework.service.SysLoginService;
import org.fund.framework.service.SysRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @Author Moro
 * @Date 2022/3/12 23:53
 * @title RegisterController
 */
@RestController
@Api(tags = "注册")
@RequestMapping(value ="/register")
public class RegisterController {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private EmailService emailService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysUserService sysUserService;

    public static final String verifyKeyPrefix = "verifycode";
    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public BaseResult register(@RequestBody RegisterBody registerBody){
        SysUser sysUser = sysUserService.selectUserByUserName(registerBody.getUserName());
        if (!Objects.isNull(sysUser)){
           return BaseResult.error(21001, "该用户已存在",registerBody);
        }
        String  code = redisCache.getCacheObject(verifyKeyPrefix + registerBody.getUserName());
        if (!StringUtils.isEmpty(code)){
            if (code.equals(registerBody.getCode())){
                registerService.register(registerBody);
                redisCache.deleteObject(verifyKeyPrefix + registerBody.getUserName());
                String token = loginService.login(registerBody.getUserName(), registerBody.getPassword());
                return BaseResult.success(token);
            }
        }
        return BaseResult.error(21000, "验证码已过期或验证码错误请重新验证");
    }
    @ApiOperation(value = "发送验证码")
    @PostMapping("/sendcode")
    public BaseResult sendCode(@RequestBody RegisterBody registerBody){
        String cacheObject = redisCache.getCacheObject(verifyKeyPrefix + registerBody.getUserName());
        if (StringUtils.isNotBlank(cacheObject)){
            return BaseResult.error(21002, "验证码已发送请稍后再试");
        }
        boolean flag = emailService.sendEmailVerificationCode(registerBody.getUserName(), registerBody.getEmail());
        return BaseResult.success(flag);
    }
}
